package com.yxs.yapp.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Ynet {
    private static final String TAG = "Ynet";
    private static final ExecutorService executor = Executors.newCachedThreadPool();

    private Ynet() {}

    /**
     * 检查网络是否可用
     */
    public static boolean isNetAvailable(Context context) {
        try {
            ConnectivityManager connectivityManager = 
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivityManager == null) {
                return false;
            }
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            return activeNetworkInfo != null && activeNetworkInfo.isConnected();
        } catch (SecurityException e) {
            Log.e(TAG, "网络权限可能未授予", e);
            return false;
        }
    }

    /**
     * 检查是否是WiFi连接
     */
    public static boolean isWifiConnected(Context context) {
        try {
            ConnectivityManager connectivityManager = 
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivityManager == null) {
                return false;
            }
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            return networkInfo != null && 
                networkInfo.isConnected() && 
                networkInfo.getType() == ConnectivityManager.TYPE_WIFI;
        } catch (SecurityException e) {
            Log.e(TAG, "网络权限可能未授予", e);
            return false;
        }
    }

    /**
     * 检查是否是移动数据连接
     */
    public static boolean isMobileDataConnected(Context context) {
        try {
            ConnectivityManager connectivityManager = 
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivityManager == null) {
                return false;
            }
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            return networkInfo != null && 
                networkInfo.isConnected() && 
                networkInfo.getType() == ConnectivityManager.TYPE_MOBILE;
        } catch (SecurityException e) {
            Log.e(TAG, "网络权限可能未授予", e);
            return false;
        }
    }

    /**
     * 同步发送GET请求
     */
    public static String sendGetRequest(String urlString, Map<String, String> headers) throws IOException {
        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(urlString);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setConnectTimeout(15000);
            connection.setReadTimeout(15000);

            // 设置请求头
            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                InputStream inputStream = connection.getInputStream();
                reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                StringBuilder response = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                return response.toString();
            } else {
                throw new IOException("HTTP error code: " + responseCode);
            }
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    Log.e(TAG, "关闭读取器错误", e);
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    /**
     * 同步发送POST请求
     */
    public static String sendPostRequest(String urlString, String postData, Map<String, String> headers) throws IOException {
        return sendPostRequest(urlString, postData, headers, "application/x-www-form-urlencoded");
    }

    /**
     * 同步发送POST请求（指定Content-Type）
     */
    public static String sendPostRequest(String urlString, String postData, 
                                         Map<String, String> headers, String contentType) throws IOException {
        HttpURLConnection connection = null;
        OutputStream outputStream = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(urlString);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setConnectTimeout(15000);
            connection.setReadTimeout(15000);
            connection.setDoOutput(true);

            // 设置默认Content-Type
            if (contentType != null) {
                connection.setRequestProperty("Content-Type", contentType);
            }

            // 设置请求头
            if (headers != null) {
                for (Map.Entry<String, String> entry : headers.entrySet()) {
                    connection.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }

            // 写入POST数据
            if (postData != null) {
                outputStream = connection.getOutputStream();
                outputStream.write(postData.getBytes(StandardCharsets.UTF_8));
                outputStream.flush();
            }

            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK || 
                responseCode == HttpURLConnection.HTTP_CREATED) {
                InputStream inputStream = connection.getInputStream();
                reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
                StringBuilder response = new StringBuilder();
                String line;

                while ((line = reader.readLine()) != null) {
                    response.append(line);
                }
                return response.toString();
            } else {
                throw new IOException("HTTP error code: " + responseCode);
            }
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    Log.e(TAG, "关闭输出流错误", e);
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    Log.e(TAG, "关闭读取器错误", e);
                }
            }
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

    /**
     * 异步发送GET请求
     */
    public static void sendGetRequestAsync(final String urlString, final Map<String, String> headers, 
                                           final NetworkCallback callback) {
        executor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        String response = sendGetRequest(urlString, headers);
                        if (callback != null) {
                            callback.onSuccess(response);
                        }
                    } catch (IOException e) {
                        if (callback != null) {
                            callback.onError(e.getMessage());
                        }
                    }
                }
            });
    }

    /**
     * 异步发送POST请求
     */
    public static void sendPostRequestAsync(final String urlString, final String postData, 
                                            final Map<String, String> headers, final NetworkCallback callback) {
        executor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        String response = sendPostRequest(urlString, postData, headers);
                        if (callback != null) {
                            callback.onSuccess(response);
                        }
                    } catch (IOException e) {
                        if (callback != null) {
                            callback.onError(e.getMessage());
                        }
                    }
                }
            });
    }

    /**
     * 发送JSON POST请求
     */
    public static String sendJsonPostRequest(String urlString, String jsonData, 
                                             Map<String, String> headers) throws IOException {
        return sendPostRequest(urlString, jsonData, headers, "application/json");
    }

    /**
     * 异步发送JSON POST请求
     */
    public static void sendJsonPostRequestAsync(final String urlString, final String jsonData, 
                                                final Map<String, String> headers, final NetworkCallback callback) {
        executor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        String response = sendJsonPostRequest(urlString, jsonData, headers);
                        if (callback != null) {
                            callback.onSuccess(response);
                        }
                    } catch (IOException e) {
                        if (callback != null) {
                            callback.onError(e.getMessage());
                        }
                    }
                }
            });
    }

    /**
     * 网络请求回调接口
     */
    public interface NetworkCallback {
        void onSuccess(String response);
        void onError(String errorMessage);
    }

    /**
     * 关闭线程池（在应用退出时调用）
     */
    public static void shutdown() {
        executor.shutdown();
    }
}
